'''
    Goblinoid: Experience all of MediaGoblin on an Android Device
    Copyright (C) 2015 Dylan Jeffers

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from __future__ import print_function
import os
import webbrowser
import json
from os.path import join
from pypump import PyPump, Client

from goblinoid.services.pump_service import UserStore


def load_user(user_dir):
        f = open(join(user_dir, ('user.json')), 'r')
        webfinger = json.load(f)['webfinger']
        print('got webfinger from file: {0}'.format(webfinger))
        return create_pump_profile(webfinger)


def user_logged_on(user_dir):
    # checking store directory
    if not os.path.exists(user_dir):
        os.makedirs(join(user_dir))
        return False
    # has opened app before:
    else:
        if not os.path.isfile(join(user_dir, 'user.json')):
            remove_credential(user_dir)
            return False
        else:
            return True


def remove_credential(user_dir):
    try:
        os.remove(join(user_dir, 'credentials.json'))
# Note: figure out which error is caused
    except:
        print('tried to remove credentials.json, but doesnt exist, continue..')
    try:
        os.remove(join(user_dir, 'user.json'))
    except:
        print('tried to remove user.json, but doesnt exist, continue..')


def add_credential(user_dir, webfinger):
    f = open(join(user_dir, ('user.json')), 'w')
    print('credential')
    x = {'webfinger': webfinger}
    json.dump(x, f)
    f.close()


def create_pump_profile(webfinger):
    # create/load store from hard disk:

    client = Client(
        webfinger=webfinger,
        name="Goblinoid",
        type="native"
    )

    def web_verifier(url):
        webbrowser.open(url)
        return None

    # loading store and creating pump object
    print('got to store')
    userStore = UserStore.load(webfinger, None)

    pump = PyPump(
        store=userStore,
        client=client,
        verifier_callback=web_verifier
    )
    return pump


def verify_new_user(pump, token):
    pump.verifier(token)
    print('finished pump verification')
    return pump
